package com.jubotech.framework.netty.handler.socket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.google.protobuf.util.JsonFormat;
import com.jubotech.business.web.domain.WxAccountInfo;
import com.jubotech.business.web.service.WxAccountService;
import com.jubotech.framework.netty.async.AsyncTaskService;
import com.jubotech.framework.netty.common.Constant;
import com.jubotech.framework.netty.handler.MessageHandler;
import com.jubotech.framework.netty.utils.MessageUtil;

import Jubo.JuLiao.IM.Wx.Proto.FriendPushNotice.FriendPushNoticeMessage;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass.EnumErrorCode;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass.EnumMsgType;
import Jubo.JuLiao.IM.Wx.Proto.TransportMessageOuterClass.TransportMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class FriendPushNoticeHandler implements MessageHandler{
	@Autowired
	private WxAccountService weChatAccountService;
	@Autowired
	private AsyncTaskService asyncTaskService;

	/**
	 * 手机端主动推送好友列表消息
	 * 
	 * @author wechatno:tangjinjinwx
     * @blog http://www.wlkankan.cn
	 */
	@Async
	public void handleMsg(ChannelHandlerContext ctx, TransportMessage vo) {
		try {
			FriendPushNoticeMessage req = vo.getContent().unpack(FriendPushNoticeMessage.class);
			log.debug(JsonFormat.printer().print(req));
			// 把消息转发给pc端
			// a、根据wechatId找到accountid
			// b、通过accountid找到account
			// c、通过account账号找到通道
			WxAccountInfo account = weChatAccountService.findWeChatAccountInfoByWeChatId(req.getWeChatId());

			asyncTaskService.msgSend2pc(req.getWeChatId(), EnumMsgType.FriendPushNotice, req);
			if (null != account) {
				// 异步保存到数据库
				asyncTaskService.friendListSave(req, account);
			}
			// 告诉客户端消息已收到
			MessageUtil.sendMsg(ctx, EnumMsgType.MsgReceivedAck, vo.getAccessToken(), vo.getId(), null);

		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.sendErrMsg(ctx, EnumErrorCode.InvalidParam, vo.getId(), Constant.ERROR_MSG_DECODFAIL);
		}
	}

}